package top.sehnsucht;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import top.sehnsucht.utils.ExcelUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description:
 * @Author: Cai
 * @CreateTime: 2021/10/29
 */

public class UploadServlet extends HttpServlet {
    private Logger logger=Logger.getLogger(this.getClass());
    private Lock lock = new ReentrantLock();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        lock.lock();
        try {
            req.setCharacterEncoding("utf-8");
            resp.setCharacterEncoding("utf-8");
            resp.setContentType("text/html; charset=UTF-8");
            logger.info("单次请求" + req);

            //判断文件是否可以上传
            boolean isMultipart = ServletFileUpload.isMultipartContent(req);
            //可以上传,有问题就报异常
            if (isMultipart) {
                //创建一个FileItem工厂，通过工厂创建文件上传核心组件ServletFileUpload对象
                ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
                try {
                    //通过核心上传组件解析request请求，获取表单的所有表单项，表单的每一个表单项对应一个FileItem
                    List<FileItem> items = upload.parseRequest(req);
                    Iterator<FileItem> it = items.iterator();
                    for (FileItem item : items) {

                        if (item.isFormField()) {
                            logger.error("其他类型");
                        } else {
                            for (String s : item.getName().split("\\.")) {
                                logger.error(s);
                            }

                            if (!item.getName().split("\\.")[item.getName().split("\\.").length - 1].equals("xls")) {
                                continue;
                            }
                            String filename = item.getName();
                            String path = req.getSession().getServletContext().getRealPath("/") + "\\1";
                            File file = new File(path);
                            if (!file.exists()) {
                                file.mkdirs();
                            }
                            file = new File(path, filename);
                            item.write(file);
                            logger.debug(filename + "上传成功");
                            ExcelUtil.readExcelFile(filename.split("\\.")[0],path + "\\" + filename);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
            logger.debug("解锁");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
